package com.tee.live.im.core.server.handler;

import com.alibaba.fastjson.JSON;
import com.tee.im.constants.AppIdEnum;
import com.tee.im.constants.ImMsgCodeEnum;
import com.tee.im.dto.ImMsgBody;
import com.tee.im.interfaces.ImTokenRpc;
import com.tee.live.im.core.server.common.ChannelHandlerContextCache;
import com.tee.live.im.core.server.common.ImContextUtils;
import com.tee.live.im.core.server.common.ImMsg;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 登录消息处理器
 *
 * @author tee
 * @date 2025/10/22
 */
@Component
public class LoginImMsgHandler implements SimplyHandler {

    @DubboReference
    private ImTokenRpc imTokenRpc;

    @Resource
    private StringRedisTemplate redisTemplate;

    private static final Logger log = LoggerFactory.getLogger(LoginImMsgHandler.class);

    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg imMsg) {
        // 登录消息处理
        if (ImContextUtils.getUserId(ctx) != null) {
            return;
        }
        byte[] body = imMsg.getBody();
        if (body == null || body.length == 0) {
            log.error("登录消息体为空");
            ctx.close();
            throw new IllegalArgumentException("body error");
        }
        ImMsgBody imMsgBody = JSON.parseObject(body, ImMsgBody.class);
        int appId = imMsgBody.getAppId();
        long userIdFromMsg = imMsgBody.getUserId();
        String token = imMsgBody.getToken();

        if (StringUtils.isEmpty(token) || appId < 10000 || userIdFromMsg < 10000) {
            log.error("param error,imMsg is {}", imMsg);
            ctx.close();
            throw new IllegalArgumentException("token error");
        }
        Long userId = imTokenRpc.getUserIdByToken(token);
        if (userId != null && userId.equals(userIdFromMsg)) {
            ChannelHandlerContextCache.put(userId, ctx);
            ImContextUtils.setUserId(ctx, userId);
            ImContextUtils.setAppId(ctx, appId);
            ImMsgBody respBody = new ImMsgBody();
            respBody.setAppId(AppIdEnum.SY_LIVE_BIZ.getCode());
            respBody.setUserId(userId);
            respBody.setData("true");
            ImMsg respMsg = ImMsg.build(ImMsgCodeEnum.IM_LOGIN_MSG.getCode(), JSON.toJSONString(respBody));
//            redisTemplate.opsForValue().set("");
            log.info("登录成功，userId: {}, appId: {}", imMsgBody.getUserId(), imMsgBody.getAppId());
            ctx.writeAndFlush(respMsg);
        } else {
            ctx.close();
            log.error("登录失败，token校验失败，userId: {}, token: {}", imMsgBody.getUserId(), token);
            throw new IllegalArgumentException("login failed");
        }
    }

}
